package com.myjpa.generate;

import lombok.Getter;
import lombok.Setter;

import java.io.*;

/**
 * @author: yaoll
 * @date: 2020-09-04
 * @verison: 1.0
 */
@Getter
@Setter
public class Generator {


	public void generate(GenerateContext ctx) {

		ctx.init();

		EntityGenerator entityGenerator = new EntityGenerator();
		entityGenerator.generate(ctx);
		createFile(ctx.getEntityClass() + ".java", ctx.getPath() + "/entity", entityGenerator.getBuff().toString(), ctx.isOverrideFile());

		boolean withModel = ctx.isWithModel();
		if (withModel) {
			ModelGenerator modelGenerator = new ModelGenerator();
			modelGenerator.generate(ctx);
			createFile(ctx.getModelClass() + ".java", ctx.getPath() + "/model", modelGenerator.getBuff().toString(), ctx.isOverrideFile());
		}

		RepositoryGenerator repositoryGenerator = new RepositoryGenerator();
		repositoryGenerator.generate(ctx);
		createFile(ctx.getRepositoryClass() + ".java", ctx.getPath() + "/repository", repositoryGenerator.getBuff().toString(), ctx.isOverrideFile());

		ServiceGenerator serviceGenerator = new ServiceGenerator();
		serviceGenerator.generate(ctx);
		createFile(ctx.getServiceClass() + ".java", ctx.getPath() + "/service", serviceGenerator.getBuff().toString(), ctx.isOverrideFile());

		ControllerGenerator controllerGenerator = new ControllerGenerator();
		controllerGenerator.generate(ctx);
		createFile(ctx.getControllerClass() + ".java", ctx.getPath() + "/controller", controllerGenerator.getBuff().toString(), ctx.isOverrideFile());

	}

	private void createFile(String filename, String filepath, String content, boolean overrideFile) {
		File path = new File(filepath);
		if (!path.exists()) {
			path.mkdirs();
		}
		File file = new File(path, filename);

		if (file.exists() && !overrideFile) {
			return;
		}

		FileOutputStream fis = null;
		OutputStreamWriter write = null;

		try {
			fis = new FileOutputStream(file);
			write = new OutputStreamWriter(fis);
			write.write(content);
			write.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (write != null) {
				try {
					write.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}


	}
}
